package com.keycloak.admin.services;

import com.keycloak.admin.client.KeycloakAdminClient;
import com.keycloak.admin.config.Myprops;
import com.keycloak.admin.map.ClientMap;
import com.keycloak.admin.model.params.*;
import com.keycloak.admin.model.params.main.DriverInfoVo;
import com.keycloak.admin.model.params.main.DrivinLicense;
import com.keycloak.admin.model.params.main.IdentityCard;
import com.keycloak.admin.model.params.main.TravelLicense;
import com.keycloak.admin.model.params.vo.*;
import com.keycloak.admin.utils.CheckUtils;
import com.keycloak.admin.utils.KeycloakClientManager;
import com.keycloak.admin.utils.MainServerUtils;
import com.keycloak.admin.utils.Md5Utils;
import com.mashape.unirest.http.HttpResponse;
import com.sun.org.apache.xpath.internal.SourceTree;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Service
public class UserInfo {

    @Resource
    Myprops myProps;

    @Resource
    ClientMap clientMap;

    @Autowired
    VCodeService vCodeService;

    @Autowired
    RequestPostCallbackService requestPostCallbackService;

    @Autowired
    MainServerUtils mainServerUtils;


    //获取client token
    public ReturnParams getClientToken(String clientId) {
        String clientSecret = clientMap.getClientSecret(clientId);
        String masterToken = getMasterToken(clientId, clientSecret).getToken().getToken();
        return new ReturnParams(0, "success", masterToken);

    }

    //获取验证码
    public ReturnParams getVCode(GetVCodeParams request) {
       /*
        Pattern compile = Pattern.compile(CheckUtils.REGEX_MOBILE);
        Matcher matcher = compile.matcher(request.getCell());
        if(!matcher.find()){
          return  new ReturnParams(1, "请输入正确的手机号码！", null);
        }*/
        if (request.getCell().length() != 11) {
            //如果手机号码无效，则抛出异常
            return new ReturnParams(1, "请输入正确的手机号码！", null);
        }
        return vCodeService.sendVCode(request.getCell(), 1);
    }

    /**
     * 查询用户
     *
     * @return
     */
    public List<UserRepresentationNew> searchUsers(String cell, KeycloakAdminClient client) {

        List<UserRepresentationNew> users = new ArrayList<>();
        try {
            List<UserRepresentationNew> user = client.getRealmUsers( myProps.getKeycloakRelamName(), "?username=" + cell);

            if (user != null && user.size() > 0) {
                for (int i = 0; i < user.size(); i++) {
                    if (cell.equalsIgnoreCase(user.get(i).getUsername())) {
                        users.add(user.get(i));
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return users;
    }


    //用户注册
    public ReturnParams userReg(RegParams regParams, String clientId,HttpServletRequest request1) {
        String cell = regParams.getCell();
        String vcode = regParams.getVcode();
        String password = regParams.getPassword();
        //String clientSecret = ClientMap.getClientSecret(clientId);

        try {

            if ((vcode != null && !"".equalsIgnoreCase(vcode))) {
                //综合检查手机短信验证码
                CheckUtils.checkCellAndVCode(cell, vcode, vCodeService.getvCodeMap());//综合检查手机短信验证码

                //未失效则移除这一条验证码
                vCodeService.removeVCode(cell);
            }

            //判断用户是否存在
            KeycloakAdminClient client = null;
            if (KeycloakClientManager.getClientMap(clientId) != null) {
                client = KeycloakClientManager.getClientMap(clientId);
            } else {
                client = getMasterToken(clientId, clientMap.getClientSecret(clientId));
                KeycloakClientManager.setClientMap(clientId, client);
            }

            List<UserRepresentationNew> users = searchUsers(cell, client);
            String loginPassword = "";
            if (users.size() == 0) {
                //用户不存在时，必须带上验证码 否则注册/初次登陆失败
                if(vcode == null || "".equalsIgnoreCase(vcode)){
                    return new ReturnParams(1,"账户名密码不匹配！",null);
                }

                KeycloakUserParams key = new KeycloakUserParams();
                key.setUsername(cell);
                String defalutPassword = getDefalutPassword();
                Map<String, Object> attributes = new HashMap<>();
                attributes.put("default_password", defalutPassword);
                attributes.put("password_setup", "false");
                key.setAttributes(attributes);
                createUser(key, clientId, password);

                //将默认密码存入user
                Integer result = createPassword(cell, defalutPassword, client, "reg");
                loginPassword = defalutPassword;

                //往主服务系统增加数据
                List<UserRepresentationNew> user1 = searchUsers(cell, client);
                if (user1.size() > 0) {
                    if("driver".equalsIgnoreCase(clientId)){
                        Boolean aBoolean = mainServerUtils.userReg(cell, user1.get(0).getId(),clientId);
                    }else if("passenger".equalsIgnoreCase(clientId)){
                        mainServerUtils.passengerReg(cell);
                    }
                }

            } else {
                //去登陆获取accessToken
                Map<String, Object> attributes = users.get(0).getAttributes();
                if (attributes != null) {
                    if ("false".equalsIgnoreCase(attributes.get("password_setup").toString().replace("[", "").replace("]", ""))) {
                        String default_password = attributes.get("default_password").toString().replace("[", "").replace("]", "");
                        //未更新过密码
                         if(password != null && !"".equalsIgnoreCase(password)){
                            if(!default_password.equals(password)){
                                return new ReturnParams(1,"账户名密码不匹配！",null);
                            }
                         }
                        loginPassword = default_password;

                    } else {
                        if (password == null || "".equalsIgnoreCase(password)) {
                            loginPassword = attributes.get("default_password").toString().replace("[", "").replace("]", "");
                        } else {
                            loginPassword = password;
                        }

                    }
                }
            }

            //往主服务系统增加数据
           /* List<UserRepresentationNew> user1 = searchUsers(cell, client);
            if (user1.size() > 0) {
                Boolean aBoolean = mainServerUtils.userReg(cell, user1.get(0).getId());
            }*/


            //去登陆获取用户accessToken
            CreateUserPasswordParams createUserPassword = new CreateUserPasswordParams();
            createUserPassword.setCell(cell);
            createUserPassword.setPassword(loginPassword);
            ReturnParams returnParams = userLogin(createUserPassword, clientId);


            if (returnParams.getCode() != 0) {
                return new ReturnParams(1, returnParams.getData().toString(), null);
            }

            //用户登录（网安推送）
            mainServerUtils.driverLoginForWanganPush(cell,clientId,regParams,request1);



            return new ReturnParams(0, "success", returnParams.getData());
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnParams(1, "登录失败！" + e.getMessage(), null);
        }

    }


    public String getDefalutPassword() {
        try {
            Random random = new Random();
            String result = "";
            for (int i = 0; i < 6; i++) {
                result += random.nextInt(10);
            }
            System.out.println(result);

            return Md5Utils.MD5(result);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }

    /**
     * 删除用户
     *
     * @return
     */
    public ReturnParams deleteUser(DeleteUserParams deleteUserParams, String clientId) {
        String clientSecret = clientMap.getClientSecret(clientId);
        String cell = deleteUserParams.getCell();
        try {
            KeycloakAdminClient client = null;
            if (KeycloakClientManager.getClientMap(clientId) != null) {
                client = KeycloakClientManager.getClientMap(clientId);
            } else {
                client = getMasterToken(clientId, clientMap.getClientSecret(clientId));
                KeycloakClientManager.setClientMap(clientId, client);
            }
            List<UserRepresentationNew> users = client.getRealmUsers( myProps.getKeycloakRelamName(), "?username=" + cell);
            if (users != null && users.size() > 0) {
                for (int i = 0; i < users.size(); i++) {
                    String id = users.get(i).getId();
                    client.deleteRealmUser( myProps.getKeycloakRelamName(), id);
                }
            } else {
                return new ReturnParams(1, "error", "用户不存在!");
            }
            return new ReturnParams(0, "success", "删除用户成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnParams(1, "error", "删除失败！" + e.getMessage());
        }
    }

    /**
     * 根据accessToken查询用户信息
     */
    public synchronized ReturnParams getUserInfoForMianServer(String clientId,String accessToken){

        String clientSecret = clientMap.getClientSecret(clientId);
        DriverInfoDetailsVo driverInfoDetailsVo = new DriverInfoDetailsVo();
        String bearer_ = "";
        if(accessToken != null){
            bearer_ = accessToken.replace("Bearer ", "");
            System.out.println(accessToken);
        }

        try {
            return requestPostCallbackService.getKeycloakUserInfoByAccessToken( myProps.getKeycloakRelamName(), clientId, clientSecret, bearer_);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnParams(1,"解析失败！"+e.getMessage(),null);
        }

    }

    /**
     * 查询用户基本信息
     *
     * @return
     */
    public ReturnParams getUserInfo( String clientId,String accessToken) {
        String clientSecret = clientMap.getClientSecret(clientId);
        DriverInfoDetailsVo driverInfoDetailsVo = new DriverInfoDetailsVo();
        String bearer_ = "";
        if(accessToken != null){
             bearer_ = accessToken.replace("Bearer ", "");
            // accessToken = substring1.substring(7, substring1.length() - 1);
            //System.out.println(accessToken);
        }
        try {
            //根据accessToken获取用户名
            ReturnParams userInfoByAccessToken1 = requestPostCallbackService.getUserInfoByAccessToken( myProps.getKeycloakRelamName(), clientId, clientSecret, bearer_);
            if(userInfoByAccessToken1.getCode() != 0) //解析token失败
             return userInfoByAccessToken1;

            String userInfoByAccessToken = userInfoByAccessToken1.getMsg();
            KeycloakAdminClient client = null;
            if (KeycloakClientManager.getClientMap(clientId) != null) {
                client = KeycloakClientManager.getClientMap(clientId);
            } else {
                client = getMasterToken(clientId, clientMap.getClientSecret(clientId));
                KeycloakClientManager.setClientMap(clientId, client);
            }

            List<UserRepresentationNew> user = client.getRealmUsers( myProps.getKeycloakRelamName(), "?username=" + userInfoByAccessToken);
            List<UserRepresentationNew> users = new ArrayList<>();
            if (user != null && user.size() > 0) {
                for (int i = 0; i < user.size(); i++) {
                    if (userInfoByAccessToken.equalsIgnoreCase(user.get(i).getUsername())) {
                        users.add(user.get(i));
                    }
                }
                if (users.size() > 0) {
                    driverInfoDetailsVo.setUserRepresentation(users.get(0));
                } else {
                    return new ReturnParams(1, "用户不存在！", null);
                }
            }

            ComplateDriverInfoVerifyVo complateDriverInfoVerifyVo = null;
            complateDriverInfoVerifyVo = mainServerUtils.sendOrderToMainServer("", userInfoByAccessToken);
             if(complateDriverInfoVerifyVo == null){
                 return new ReturnParams(1, "系统异常！", null);
             }

            //  if (complateDriverInfoVerifyVo == null) complateDriverInfoVerifyVo = new ComplateDriverInfoVerifyVo();
          //  complateDriverInfoVerifyVo.setPhone(userInfoByAccessToken);/*
         /*   if(complateDriverInfoVerifyVo.getDriverFlag() == null || complateDriverInfoVerifyVo.getVehicleFlag() == null){
                //直接跳转司机入驻界面的标志位
                complateDriverInfoVerifyVo.setDriverFlag(4);
                complateDriverInfoVerifyVo.setVehicleFlag(4);
            }*/
            driverInfoDetailsVo.setDriverInfoVerify(complateDriverInfoVerifyVo);

            DriverInfoVo driverInfoVo = tranformData(users.size() > 0 ? user.get(0): null , complateDriverInfoVerifyVo);
            driverInfoVo.setPhone(userInfoByAccessToken);

            return new ReturnParams(0, "success", driverInfoVo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnParams(1, "error", "查询失败！" + e.getMessage());
        }
    }

    /**
     * 数据转换
     * @return
     */
    private DriverInfoVo tranformData(UserRepresentationNew userRepresentationNew,ComplateDriverInfoVerifyVo cVo){
        DriverInfoVo driverInfoVo = new DriverInfoVo();
        try {

         if(userRepresentationNew != null){
             driverInfoVo.setId(userRepresentationNew.getId());
             Map<String, Object> attributes = userRepresentationNew.getAttributes();
             if (attributes != null) {
                 driverInfoVo.setPasswordSetup(attributes.get("password_setup").toString().replace("[", "").replace("]", ""));
             }
         }

         if(cVo != null){
             driverInfoVo.setHaveVehicle(cVo.getHaveVehicle());
             driverInfoVo.setCityId(cVo.getCityId());
             driverInfoVo.setCityName(cVo.getCityName());
             driverInfoVo.setTid(cVo.getTid());
             driverInfoVo.setSid(cVo.getSid());
             driverInfoVo.setDriverPhoto(cVo.getDriverPhoto());

             if(cVo.getDriverFlag() != null){
                 driverInfoVo.setDriverFlag(cVo.getDriverFlag());
             }else{
                 driverInfoVo.setDriverFlag(4);
             }

             if(cVo.getVehicleFlag() != null){
                 driverInfoVo.setVehicleFlag(cVo.getVehicleFlag());
             }else{
                 driverInfoVo.setVehicleFlag(4);
             }

             //驾驶证信息
             DrivinLicense dl= new DrivinLicense();
             dl.setUserName(cVo.getUserName());
             dl.setFirstIssueDate(cVo.getFirstIssueDate());
             dl.setLicenseNumber(cVo.getLicenseId());
             dl.setType(cVo.getLicenseType());
             if(cVo.getGender() != null){
                 if("男".equalsIgnoreCase(cVo.getGender())){
                     dl.setGender(1);
                 }else if("女".equalsIgnoreCase(cVo.getGender())){
                     dl.setGender(2);
                 }else {
                     dl.setGender(0);
                 }
             }
             dl.setExpiryDateFrom(cVo.getDriverLicenseOn());
             dl.setDuration(cVo.getDriverLicensetime());
             dl.setAddress(cVo.getDriverLicenseAddress());
             dl.setRecordNumber(cVo.getDriverLicenseNo());
             dl.setFacePath(cVo.getDriverLicenseFacePath());
             dl.setBackPath(cVo.getDriverLicenseBackPath());
             driverInfoVo.setDrivinLicense(dl);


             //用户身份信息
             IdentityCard id = new IdentityCard();
             id.setUserName(cVo.getUserName());
             id.setIdNumber(cVo.getIdCardNo());
             if(cVo.getGender() != null){
                 if("男".equalsIgnoreCase(cVo.getGender())){
                     id.setGender(1);
                 }else if("女".equalsIgnoreCase(cVo.getGender())){
                     id.setGender(2);
                 }else {
                     id.setGender(0);
                 }
             }
             id.setNation(cVo.getNation());
             id.setBirthday(cVo.getBirth());
             id.setAddress(cVo.getAddress());
             id.setExpiryDateFrom(cVo.getIdCardEffectiveStartTime());
             id.setExpiryDateTo(cVo.getIdCardEffectiveEndTime());
             id.setFacePath(cVo.getIdFacePath());
             id.setBackPath(cVo.getIdBackPath());
             driverInfoVo.setIdentityCard(id);

             //行驶证信息
             TravelLicense tl = new TravelLicense();
             tl.setRegister(cVo.getVehicleRegisterDate());
             tl.setAddress(cVo.getVeAddress());
             tl.setIssueDate(cVo.getIssueDate());
             tl.setVehicleType(cVo.getDrivingPermitVehicleType());
             tl.setPlateNum(cVo.getVehicleNo());
             tl.setUseCharacter(cVo.getUsageType());
             tl.setEngineNum(cVo.getEngineId());
             tl.setBrand(cVo.getBrand());
             tl.setOwner(cVo.getOwner());
             tl.setVin(cVo.getVin());
             tl.setUnladenMass(cVo.getQualityOfPreparation());
             tl.setOverallDimension(cVo.getDimension());
             tl.setInspectionRecord(cVo.getCheckRecord());
             tl.setAppprovedPassengerCapacity(cVo.getSeats());
             tl.setGrossMass(cVo.getTotalMass());
             tl.setVehiclePhoto(cVo.getVehiclePhoto());
             tl.setTravelLicenseNegative(cVo.getTravelLicenseNegative());
             tl.setTravelLicensePositive(cVo.getTravelLicensePositive());
             driverInfoVo.setTravelLicense(tl);

         }else{
             driverInfoVo.setVehicleFlag(4);
             driverInfoVo.setDriverFlag(4);
             driverInfoVo.setDrivinLicense(new DrivinLicense());
             driverInfoVo.setIdentityCard(new IdentityCard());
             driverInfoVo.setTravelLicense(new TravelLicense());
         }

        } catch (Exception e) {
            e.printStackTrace();
        }
           return driverInfoVo;

    }



    //设置密码services
    private Integer createPassword(String cell, String password, KeycloakAdminClient client, String flag) {
        try {
            List<UserRepresentationNew> user = client.getRealmUsers( myProps.getKeycloakRelamName(), "?username=" + cell);
            List<UserRepresentationNew> users = new ArrayList<>();
            if (user != null && user.size() > 0) {
                for (int i = 0; i < user.size(); i++) {
                    if (cell.equalsIgnoreCase(user.get(i).getUsername())) {
                        users.add(user.get(i));
                    }
                }
            }
            if (users != null && users.size() > 0) {
                CredentialRepresentation ce = new CredentialRepresentation();
                ce.setTemporary(false);
                ce.setType("password");
                ce.setValue(password);
                client.resetPassword( myProps.getKeycloakRelamName(), users.get(0).getId(), ce);

                if ("reset".equalsIgnoreCase(flag)) {
                    users.get(0).getAttributes().put("password_setup", null);
                    users.get(0).getAttributes().put("password_setup", "true");
                    users.get(0).getAttributes().put("default_password", null);
                    users.get(0).getAttributes().put("default_password", password);
                    client.updateRealmUser( myProps.getKeycloakRelamName(), users.get(0));
                }

            } else {
                return 1;//用户不存在
            }
            return 0;//设置密码成功!
        } catch (Exception e) {
            e.printStackTrace();
            return -1;//系统错误
        }

    }

    /**
     * 设置用户密码
     *
     * @return
     */
    public ReturnParams createPassword(CreateUserPasswordParams createUserPasswordParams, String clientId,String accessToken) {
        String cell = "";
        String password = createUserPasswordParams.getPassword();
        String clientSecret = clientMap.getClientSecret(clientId);
        String vcode = createUserPasswordParams.getVcode();

        if(password == null || password.length() != 32)  return new ReturnParams(1, "密码格式不正确,请重新设置！", null);
        String bearer_ = "";
        if(accessToken != null){
            bearer_ = accessToken.replace("Bearer ", "");
            // accessToken = substring1.substring(7, substring1.length() - 1);
            System.out.println(accessToken);
        }

        try {
            //根据accessToken获取用户名
            ReturnParams userInfoByAccessToken1 = requestPostCallbackService.getUserInfoByAccessToken( myProps.getKeycloakRelamName(), clientId, clientSecret, bearer_);
            if(userInfoByAccessToken1.getCode() != 0) //解析token失败
                return userInfoByAccessToken1;

            cell = userInfoByAccessToken1.getMsg();

            //综合检查手机短信验证码
            CheckUtils.checkCellAndVCode(cell, vcode, vCodeService.getvCodeMap());//综合检查手机短信验证码

            //未失效则移除这一条验证码
            vCodeService.removeVCode(cell);

            KeycloakAdminClient client = null;
            if (KeycloakClientManager.getClientMap(clientId) != null) {
                client = KeycloakClientManager.getClientMap(clientId);
            } else {
                client = getMasterToken(clientId, clientMap.getClientSecret(clientId));
                KeycloakClientManager.setClientMap(clientId, client);
            }
            Integer result = createPassword(cell, password, client, "reset");

            if (result == 0) {
                return new ReturnParams(0, "更新密码成功！", "更新密码成功！");
            } else if (result == 1) {
                return new ReturnParams(1, "用户不存在！", null);
            }
            return new ReturnParams(1, "更新密码失败！", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnParams(1, "更新密码失败！" + e.getMessage(), null);
        }

    }

    /**
     * 用户登录
     *
     * @return
     */
    public ReturnParams userLogin(CreateUserPasswordParams createUserPasswordParams, String clientId) {
        String cell = createUserPasswordParams.getCell();
        String password = createUserPasswordParams.getPassword();
        AccessTokenResponse accessTokenResponse = null;
        String clientSecret = clientMap.getClientSecret(clientId);
        try {
            KeycloakAdminClient client = null;
            if (KeycloakClientManager.getClientMap(clientId) != null) {
                client = KeycloakClientManager.getClientMap(clientId);
            } else {
                client = getMasterToken(clientId, clientMap.getClientSecret(clientId));
                KeycloakClientManager.setClientMap(clientId, client);
            }
            List<UserRepresentationNew> user = client.getRealmUsers( myProps.getKeycloakRelamName(), "?username=" + cell);
            List<UserRepresentationNew> users = new ArrayList<>();
            if (user != null && user.size() > 0) {
                for (int i = 0; i < user.size(); i++) {
                    if (cell.equalsIgnoreCase(user.get(i).getUsername())) {
                        users.add(user.get(i));
                    }
                }
            }
            if (users != null && users.size() > 0) {
                //查询用户是否已有登陆session
                List<UserSessionList> sessionsByUserId = getSessionsByUserId(users.get(0).getId(), client, clientId);
                System.out.println(sessionsByUserId);
                if(sessionsByUserId != null && sessionsByUserId.size() > 0){
                    //判断在线session是在哪一个clientid下
                    for(int i = 0;i < sessionsByUserId.size();i++){

                    Map<Object, Object> clients = sessionsByUserId.get(i).getClients();
                    for(Object value : clients.values()){
                        System.out.println(value.toString());
                        if(clientId.equalsIgnoreCase(value.toString())){
                            deleteUserSession(client,sessionsByUserId.get(i).getId());
                        }
                       }

                    }

                    //清楚之前用户的缓存
                    //deteleUserSession(users.get(0).getId(),client);
                }
                String cliId = "";
                if("driver".equalsIgnoreCase(clientId)){
                     cliId = myProps.getDriverclientId();
                }else if("passenger".equalsIgnoreCase(clientId)){
                    cliId = myProps.getPassengerClientId();
                }
                List<RoleRepresentationNew> clinetRolesForUser = client.getClinetRolesForUser( myProps.getKeycloakRelamName(), users.get(0).getId(), cliId);

                client.addClientRolesToUser( myProps.getKeycloakRelamName(), users.get(0).getId(), cliId, clinetRolesForUser);

                accessTokenResponse = client.loginByPassword(cell, password, clientId);
                System.out.println("refresh:"+accessTokenResponse.getRefreshToken());

                //RefreshTokenReturn refreshTokenReturn = paseAccessToken(accessTokenResponse,clientId);
                String s = parseToken(accessTokenResponse.getToken(), clientId);

                if (s != null) {
                    AccessTokenParams accessTokenParams = new AccessTokenParams();
                    accessTokenParams.setAccessToken(s);
                    accessTokenParams.setRefreshToken(accessTokenResponse.getRefreshToken());
                    accessTokenParams.setUuid(users.get(0).getId());
                    return new ReturnParams(0, "success", accessTokenParams);
                } else {
                    return new ReturnParams(1, "error", "用户名密码不匹配!");
                }

            } else {
                return new ReturnParams(1, "error", "用户不存在!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnParams(1, "error", "登录失败！" + e.getMessage());
        }
    }

    /**
     * 根据accesstoken换取 权限之后的accesstoken
     */

    private String parseToken(String accessToken, String clientId) {


        try {
            AccessTokenResponse ace = new AccessTokenResponse();
            ace.setToken(accessToken);

            String url = myProps.getKeycloakUrl() + String.format(
                    "/auth/realms/%s/protocol/openid-connect/token",  myProps.getKeycloakRelamName());
            Map<String, Object> map = new HashMap<>();
            map.put("audience", clientId);
            map.put("grant_type", "urn:ietf:params:oauth:grant-type:uma-ticket");
            map.put("response_include_resource_name", "true");

            RefreshToken re = new RefreshToken();
            re.setAudience(clientId);
            re.setResponse_include_resource_name("true");
            return getUserObtainToken(accessToken, clientId);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    private String getUserObtainToken(String accessToken, String clientId) {

        return requestPostCallbackService.refreTokenPostman1(accessToken, clientId,  myProps.getKeycloakRelamName());

    }

    /**
     * 解析用户token
     *
     * @return
     */
    public ReturnParams parseToke(AccessTokenParams accessTokenParams, String clientId) {

        String accessToken = accessTokenParams.getAccessToken();
        try {
            AccessTokenResponse ace = new AccessTokenResponse();
            ace.setToken(accessToken);

            String url = myProps.getKeycloakUrl() + String.format(
                    "/auth/realms/%s/protocol/openid-connect/token",  myProps.getKeycloakRelamName());
            Map<String, Object> map = new HashMap<>();
            map.put("audience", clientId);
            map.put("grant_type", "urn:ietf:params:oauth:grant-type:uma-ticket");
            map.put("response_include_resource_name", "true");

            RefreshToken re = new RefreshToken();
            re.setAudience(clientId);
            re.setResponse_include_resource_name("true");
            return (requestPostCallbackService.refreTokenPostman(accessToken, clientId,  myProps.getKeycloakRelamName()));

            //String s = requestPostCallbackService.refreshToken(url, map, accessToken);

            //RefreshTokenReturn refreshTokenReturn = paseAccessToken(ace, clientId);

            //return  new ReturnParams(0,"success",refreshTokenReturn);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnParams(0, "error", e.getMessage());
        }
    }


    //获取master的token值
    public KeycloakAdminClient getMasterToken(String clientId, String clientCer) {
        try {
            System.out.println("url:"+myProps.getKeycloakUrl());
            System.out.println("relamName:"+ myProps.getKeycloakRelamName());
            System.out.println("secret::"+ myProps.getKeycloakClientSecret());

            KeycloakAdminClient client = new KeycloakAdminClient(myProps.getKeycloakUrl(), "admin", "YuedaoV5",  myProps.getKeycloakRelamName(), clientId, clientCer);
            String token = client.login().getToken();
            return client;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * keycloak 创建用户
     *
     * @throws Exception
     */
    public void createUser(KeycloakUserParams keycloakUserParams, String clientId, String password) throws Exception {
        //KeycloakAdminClient regClient = new KeycloakAdminClient("https://keycloak.yuedaowang.com", "", "", realmName, "","");

        KeycloakAdminClient client = getMasterToken(clientId, clientMap.getClientSecret(clientId));
        List<UserRepresentationNew> user1 = client.getRealmUsers( myProps.getKeycloakRelamName(), "?username=" + keycloakUserParams.getUsername());
        List<UserRepresentationNew> users = new ArrayList<>();
        if (user1 != null && user1.size() > 0) {
            for (int i = 0; i < user1.size(); i++) {
                if (keycloakUserParams.getUsername().equalsIgnoreCase(user1.get(i).getUsername())) {
                    users.add(user1.get(i));
                }
            }
        }
        boolean found = false;
        if (users.size() > 0) {
            found = true;
        }
        for (UserRepresentationNew user : users) {
            if (user.getUsername().equals(keycloakUserParams.getUsername())) {
               /* client = new KeycloakAdminClient("https://keycloak.yuedaowang.com", "admin", "YuedaoV5", realmName, clientId,"");
                String token = client.login().getToken();
*/
                //String realmToken = client.getRealmToken(realmName);

                String cliId = "08a765fd-3ea5-4427-a6df-c22bac1b8b5a";
                List<ClientRepresentation> realmClients = client.getRealmClients( myProps.getKeycloakRelamName());
                if(realmClients!=null && realmClients.size() > 0){

                   for(int i = 0 ; i < realmClients.size(); i++){
                    if(clientId.equalsIgnoreCase(realmClients.get(i).getClientId())){
                        cliId = realmClients.get(i).getId();
                    }
                   }
                }

                List<RoleRepresentationNew> clinetRolesForUser = client.getClinetRolesForUser( myProps.getKeycloakRelamName(), user.getId(), cliId);

                /*List<RoleRepresentation> roles = client.getAvailableRealmRolesForUser(
                        realmName, user.getId());
                for(RoleRepresentation role : roles)
                {
                    System.out.println("\n\nAvailable role: " + role.getName() + "\n\n");
                }*/

                //client.getAvailableRealmRolesForUser(realmName);
                found = true;
                //List<RoleRepresentationNew> roles1  = client.getRealmRolesForUser(realmName, user.getId());

                client.addClientRolesToUser( myProps.getKeycloakRelamName(), user.getId(), cliId, clinetRolesForUser);
                //client.deleteRealmRolesForUser(realmName, user.getId(), roles);
            }
        }
        if (!found) {

            UserRepresentation user = new UserRepresentation();
            user.setUsername(keycloakUserParams.getUsername());
            user.setFirstName(keycloakUserParams.getFirstName());
            user.setLastName(keycloakUserParams.getLastName());
            user.setEmail(keycloakUserParams.getEmail());
            user.setEnabled(true);
            user.setAttributes(keycloakUserParams.getAttributes());
            user.setRealmRoles(keycloakUserParams.getRealmRoles());
            client.createRealmUser( myProps.getKeycloakRelamName(), user);
            /*Thread.sleep(1000);
            List<UserRepresentationNew> users1 = new ArrayList<>();
            users1 = client.getRealmUsers(realmName, "?username="+keycloakUserParams.getUsername());
            while(users1.size() == 0){
                users1 = client.getRealmUsers(realmName, "?username="+keycloakUserParams.getUsername());
                Thread.sleep(1000);
            }*/

                /*List<ClientRepresentation> realmClients = client.getRealmClients(realmName);
                if(realmClients!=null && realmClients.size() > 0){

                   for(int i = 0 ; i < realmClients.size(); i++){
                    if(clientId.equalsIgnoreCase(realmClients.get(i).getClientId())){
                        cliId = realmClients.get(i).getId();
                    }
                   }
                }*/

            //List<RoleRepresentationNew> clinetRolesForUser = client.getClinetRolesForUser(realmName, users1.get(0).getId(), cliId);

                /*List<RoleRepresentation> roles = client.getAvailableRealmRolesForUser(
                        realmName, user.getId());
                for(RoleRepresentation role : roles)
                {
                    System.out.println("\n\nAvailable role: " + role.getName() + "\n\n");
                }*/

            //client.getAvailableRealmRolesForUser(realmName);
            //List<RoleRepresentationNew> roles1  = client.getRealmRolesForUser(realmName, user.getId());


            //client.deleteRealmRolesForUser(realmName, user.getId(), roles);

        }
    }


    /**
     * 解析token
     */
    private RefreshTokenReturn paseAccessToken(AccessTokenResponse accessToken, String clientId) {
        KeycloakAdminClient client = getMasterToken(clientId, clientMap.getClientSecret(clientId));
        client = new KeycloakAdminClient(myProps.getKeycloakUrl(), "admin", "YuedaoV5",  myProps.getKeycloakRelamName(), "", "");
        client.setToken(accessToken);
        try {
            List<RefreshToken> li = new ArrayList<>();

            RefreshToken re = new RefreshToken();
            re.setAudience(clientId);
            re.setResponse_include_resource_name("true");

            li.add(re);
            List<RefreshTokenReturn> refreshTokenReturns = client.obtainingToken( myProps.getKeycloakRelamName(), re);
            if (refreshTokenReturns != null && refreshTokenReturns.size() > 0) {
                return refreshTokenReturns.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取用户在线session
     */
      private List<UserSessionList> getSessionsByUserId(String userId, KeycloakAdminClient client,String clientId){
          try {
              List<UserSessionList> sessionsByUserId = client.getSessionsByUserId(myProps.getKeycloakRelamName(), userId, clientId);
              return sessionsByUserId;
          } catch (Exception e) {
              e.printStackTrace();
          }
             return null;
      }

    /**
     * 登出失效用户在线session
     */
    public Boolean deteleUserSession(String userId, KeycloakAdminClient client){

        try {
            LogoutVo logoutVo = new LogoutVo();
            logoutVo.setRealm(myProps.getKeycloakRelamName());
            logoutVo.setUser(userId);

            client.logoutUser(logoutVo);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
           return false;

    }


    /**
     * 用户登出
     */
    public ReturnParams userLogut(String clientId,String accessToken){
        String clientSecret = clientMap.getClientSecret(clientId);
        String bearer_ = "";
        if(accessToken != null){
            bearer_ = accessToken.replace("Bearer ", "");
            // accessToken = substring1.substring(7, substring1.length() - 1);
            System.out.println(accessToken);
        }
        try {
            //根据accessToken获取用户名
            ReturnParams userInfoByAccessToken1 = requestPostCallbackService.getUserInfoByAccessToken( myProps.getKeycloakRelamName(), clientId, clientSecret, bearer_);
            if(userInfoByAccessToken1.getCode() != 0) //解析token失败
                return userInfoByAccessToken1;

            String userInfoByAccessToken = userInfoByAccessToken1.getMsg();
            KeycloakAdminClient client = null;
            if (KeycloakClientManager.getClientMap(clientId) != null) {
                client = KeycloakClientManager.getClientMap(clientId);
            } else {
                client = getMasterToken(clientId, clientMap.getClientSecret(clientId));
                KeycloakClientManager.setClientMap(clientId, client);
            }

            List<UserRepresentationNew> user = client.getRealmUsers( myProps.getKeycloakRelamName(), "?username=" + userInfoByAccessToken);
            List<UserRepresentationNew> users = new ArrayList<>();
            if (user != null && user.size() > 0) {
                for (int i = 0; i < user.size(); i++) {
                    if (userInfoByAccessToken.equalsIgnoreCase(user.get(i).getUsername())) {
                        users.add(user.get(i));
                    }
                }
            }

            if (users != null && users.size() > 0) {
                //查询用户是否已有登陆session
                List<UserSessionList> sessionsByUserId = getSessionsByUserId(users.get(0).getId(), client, clientId);
                System.out.println(sessionsByUserId);
                if (sessionsByUserId != null && sessionsByUserId.size() > 0) {
                    //清楚之前用户的缓存
                    deteleUserSession(users.get(0).getId(), client);
                }
            }
             return new ReturnParams(0,"logout success","退出登录成功！");

            } catch (Exception e) {
            e.printStackTrace();
            return new ReturnParams(1,"logout error "+e.getMessage(),null);
        }

    }


    //删除用户某个在线session
    private void deleteUserSession(KeycloakAdminClient client,String sessionId){
        try {

            client.deletUserSessionForUser(myProps.getKeycloakRelamName(),sessionId);


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 用户迁移
     */
    public ReturnParams  userRemove(){

        String clientId = "driver";

            //主服务需要迁移的用户
            List<KeycloakDriverParams> keycloakDriverParams = mainServerUtils.removeUser();
            System.out.println(keycloakDriverParams);

            //keycloak 服务注册
            KeycloakAdminClient client = null;
            if (KeycloakClientManager.getClientMap(clientId) != null) {
                client = KeycloakClientManager.getClientMap(clientId);
            } else {
                client = getMasterToken(clientId, clientMap.getClientSecret(clientId));
                KeycloakClientManager.setClientMap(clientId, client);
            }

            if(keycloakDriverParams != null && keycloakDriverParams.size() > 0) {
                for (int i = 0; i < keycloakDriverParams.size(); i++) {
                    try {
                        List<UserRepresentationNew> users = searchUsers(keycloakDriverParams.get(i).getPhone(), client);
                        if(users != null && users.size() > 0){
                            //如果该用户在keycloak已经注册  去绑定uuid


                        }else{
                            //同步用户数据
                            KeycloakUserParams key = new KeycloakUserParams();
                            key.setUsername(keycloakDriverParams.get(i).getPhone());
                            String defalutPassword =  Md5Utils.MD5E(keycloakDriverParams.get(i).getPassword());
                            Map<String, Object> attributes = new HashMap<>();
                            attributes.put("default_password", defalutPassword);
                            attributes.put("password_setup", "true");
                            key.setAttributes(attributes);

                            createUser(key, clientId, keycloakDriverParams.get(i).getPhone());

                            //将默认密码存入user
                            createPassword(keycloakDriverParams.get(i).getPhone(), defalutPassword, client, "reset");

                        }

                        //去主服务同步用户uuid
                        List<UserRepresentationNew> use = searchUsers(keycloakDriverParams.get(i).getPhone(), client);
                        if (use.size() > 0) {
                            Boolean aBoolean = mainServerUtils.userReg(keycloakDriverParams.get(i).getPhone(), use.get(0).getId(),clientId);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("同步失败 ："+keycloakDriverParams.get(i).getPhone());
                    }
                }
            }

        return new ReturnParams(0,"success ","success");

    }

}
